<template>
  <el-tabs v-model="activeName" style="padding: 0 10px">
    <el-tab-pane label="单患者" name="单患者">
      <el-row>
        <el-col :span="24">
          <div ref="chart" style="height: 600px"></div>
        </el-col>
      </el-row>
    </el-tab-pane>
    <el-tab-pane label="历史体征" name="历史体征">
      <el-row>
        <el-col :span="24">
          <el-form :inline="true" class="demo-form-inline">
            <el-form-item label="开始时间">
              <el-date-picker
                v-model="query.END_TIME"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期时间"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间">
              <el-date-picker
                v-model="query.FROM_TIME"
                type="datetime"
                placeholder="选择日期时间"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmit">查询</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="24">
          <div ref="chartHis" style="width: 100%; height: 600px"></div>
        </el-col>
      </el-row>
    </el-tab-pane>
  </el-tabs>
</template>
<script>
import Paho from "paho-mqtt";
import { getUserListByUserType } from "@/api/table";
import request from "@/utils/request";
import dayjs from "dayjs";
import { Message } from "element-ui";
export default {
  data() {
    return {
      activeName: "单患者",
      maxXAxis: 20,
      line: null,
      option: {
        tooltip: {
          trigger: "axis",
        },
        xAxis: {
          type: "category",
          data: [],
        },
        yAxis: {
          type: "value",
        },
        legend: {
          data: [
            "CVP中心静脉平均压",
            "ETCO2",
            "FIO2",
            "PULSE",
            "SpO2",
            "呼吸",
            "体温",
            "无创收缩压",
            "无创舒张压",
            "心率",
            "有创动脉收缩压",
            "有创动脉舒张压",
          ],
        },
        series: [
          {
            name: "CVP中心静脉平均压",
            type: "line",
            data: [],
          },
          {
            name: "ETCO2",
            type: "line",
            data: [],
          },
          {
            name: "FIO2",
            type: "line",
            data: [],
          },
          {
            name: "PULSE",
            type: "line",
            data: [],
          },
          {
            name: "SpO2",
            type: "line",
            data: [],
          },
          {
            name: "呼吸",
            type: "line",
            data: [],
          },
          {
            name: "体温",
            type: "line",
            data: [],
          },
          {
            name: "无创收缩压",
            type: "line",
            data: [],
          },
          {
            name: "无创舒张压",
            type: "line",
            data: [],
          },
          {
            name: "心率",
            type: "line",
            data: [],
          },
          {
            name: "有创动脉收缩压",
            type: "line",
            data: [],
          },
        ],
      },
      optionHis: {
        tooltip: {
          trigger: "axis",
        },
        xAxis: {
          type: "category",
          data: [],
        },
        yAxis: {
          type: "value",
        },
        legend: {
          data: [
            "CVP中心静脉平均压",
            "ETCO2",
            "FIO2",
            "PULSE",
            "SpO2",
            "呼吸",
            "体温",
            "无创收缩压",
            "无创舒张压",
            "心率",
            "有创动脉收缩压",
            "有创动脉舒张压",
          ],
        },
        series: [
          {
            name: "CVP中心静脉平均压",
            type: "line",
            data: [],
          },
          {
            name: "ETCO2",
            type: "line",
            data: [],
          },
          {
            name: "FIO2",
            type: "line",
            data: [],
          },
          {
            name: "PULSE",
            type: "line",
            data: [],
          },
          {
            name: "SpO2",
            type: "line",
            data: [],
          },
          {
            name: "呼吸",
            type: "line",
            data: [],
          },
          {
            name: "体温",
            type: "line",
            data: [],
          },
          {
            name: "无创收缩压",
            type: "line",
            data: [],
          },
          {
            name: "无创舒张压",
            type: "line",
            data: [],
          },
          {
            name: "心率",
            type: "line",
            data: [],
          },
          {
            name: "有创动脉收缩压",
            type: "line",
            data: [],
          },
        ],
      },
      query: {
        MONITOR_LABEL: "",
        PATIENT_ID: "",
        VISIT_ID: "",
        OPER_ID: "",
        END_TIME: "",
        FROM_TIME: "",
      },
      mqttOptions: {
        protocol: "ws",
        host: "127.0.0.1",
        port: 4000,
      },
      dict: {
        40: "心率",
        44: "PULSE",
        49: "有创收缩压",
        50: "有创舒张压",
        51: "平均压",
        53: "收缩压",
        54: "舒张压",
        57: "收缩压",
        65: "有创动脉收缩压",
        66: "有创动脉舒张压",
        67: "动脉平均压",
        69: "中心静脉收缩压",
        70: "中心静脉舒张压",
        71: "CVP中心静脉平均压",
        75: "左房平均压",
        77: "肺动脉收缩压",
        78: "肺动脉舒张压",
        83: "颅内平均压",
        89: "无创收缩压",
        90: "无创舒张压",
        92: "呼吸",
        100: "体温",
        104: "直肠温",
        105: "鼻温",
        112: "ETCO2",
        121: "SV",
        124: "CO",
        128: "PAWP",
        148: "FIO2",
        188: "SpO2",
        190: "ST-II",
        215: "CompL",
        217: "实测潮气量",
        218: "实测PEEP",
        228: "实测FiO2",
        434: "BIS",
        436: "SQI",
        437: "SR",
        439: "EMG",
        824: "温度",
        1010: "呼吸比(I:E)",
        1020: "呼气末正压(PEEP)",
        1030: "气道峰压(PEAK)",
        1040: "潮气量(VT)",
        1050: "呼吸频率(RATE)",
        1060: "通气量(MV)",
        1070: "平台压(PLAT)",
        1080: "潮气量（机设）",
        1090: "氧浓度",
        1188: "inN2O",
        1192: "etO2",
      },
      tizheng: {},
      tizhengHis: {},
      isSetup: false,
      monitor: {},
    };
  },
  created() {
    this.data = this.$store.state.user.severFall;

    if (typeof this.data.patient_id == "undefined") {
      alert("请选择一次病人");
    } else {
      getUserListByUserType().then((res) => {
        this.arrUserName = res.data;
        console.log("getUserListByUserType结果===========>", res.data);
      });
      console.log("已知患者信息=============>", this.data);
      console.log("缓存信息==========>", this.$store.state);
      this.patientId = this.data.patient_id;
    }
  },
  mounted() {
    const self = this;
    const data = {
      ...this.data,
    };
    this.getMonitorInfo(data).then((res) => {
      self.monitor = JSON.parse(res.data);
      console.log(this.$refs.chart);
      if (typeof this.data.patient_id !== "undefined") {
        this.line = this.$echarts.init(this.$refs.chart);
        this.line.setOption(this.option);
        //添加定时器
        setInterval(this.refX, 1000);
        this.mqttInit();
      }
    });
  },
  methods: {
    onSubmit() {
      this.query.MONITOR_LABEL = this.monitor.monitorName;
      if (
        this.query.MONITOR_LABEL === null ||
        this.query.MONITOR_LABEL === ""
      ) {
        Message.warning("请等待片刻或尝试切换选项卡");
      }
      this.query.PATIENT_ID = this.data.visit_id;
      this.query.VISIT_ID = "0";
      this.query.OPER_ID = "1";
      const dataset = {};
      this.getMonitorDataLog(this.query).then((res) => {
        this.optionHis.series.forEach((item) => {
          item.data = [];
        });
        this.optionHis.xAxis.data = [];
        console.log("getMonitorDataLog结果===========>", res.data);
        const data = res.data;
        for (let i = 0; i < data.length; i++) {
          const set = data[i];
          for (let j = 0; j < set.length; j++) {
            const values = set[j].value;
            const key = set[j].key;
            for (let k = 0; k < values.length; k++) {
              console.log(
                new dayjs(values[k][0]).format("YYYY-MM-DD HH:mm:ss")
              );
              //检查dataset是否有这个时间
              if (
                dataset.hasOwnProperty(
                  new dayjs(values[k][0]).format("YYYY-MM-DD HH:mm:ss")
                )
              ) {
                dataset[new dayjs(values[k][0]).format("YYYY-MM-DD HH:mm:ss")][
                  this.dict[key]
                ] = values[k][1];
              } else {
                dataset[new dayjs(values[k][0]).format("YYYY-MM-DD HH:mm:ss")] =
                  {};
                dataset[new dayjs(values[k][0]).format("YYYY-MM-DD HH:mm:ss")][
                  this.dict[key]
                ] = values[k][1];
              }
            }
          }
        }
        console.log("dataset结果===========>", dataset);
        const his = this.$echarts.init(this.$refs.chartHis);
        his.setOption(this.optionHis);
        const keyList = Object.keys(dataset);
        for (let i = 0; i < keyList.length; i++) {
          this.optionHis.xAxis.data.push(keyList[i]);
          const itemKeyList = Object.keys(dataset[keyList[i]]);
          for (let j = 0; j < itemKeyList.length; j++) {
            this.tizhengHis[itemKeyList[j]] =
              dataset[keyList[i]][itemKeyList[j]];
          }
          console.log(this.tizhengHis);
          //遍历对象this.tizheng
          this.optionHis.series.forEach((item) => {
            item.data.push(this.tizhengHis[item.name]);
          });
        }
        his.setOption(this.optionHis);
      });
    },
    getMonitorDataLog(data) {
      return request({
        url: "MonitorData/getMonitorDataLog", // 假地址 自行替换
        method: "post",
        data,
      });
    },
    getMonitorInfo(data) {
      return request({
        url: "patient/getMonitorInfo", // 假地址 自行替换
        method: "post",
        data,
      });
    },
    refX() {
      if (!this.isSetup) {
        return;
      }
      //刷新x轴
      if (this.option.xAxis.data.length >= this.maxXAxis) {
        //移除第一个
        this.option.xAxis.data.shift();
        //添加最后一个
        this.option.xAxis.data.push(this.getTime());
      } else {
        this.option.xAxis.data.push(this.getTime());
      }
      //遍历对象this.tizheng
      this.option.series.forEach((item) => {
        if (item.data.length >= 20) {
          item.data.shift();
        }
        item.data.push(this.tizheng[item.name]);
      });
      this.line.setOption(this.option);
    },
    getTime() {
      //获取形如00:00:00的时间
      return new Date().toLocaleTimeString();
    },
    mqttInit() {
      console.log("链接Mqtt");
      const mqtt = new Paho.Client(
        this.mqttOptions.host,
        this.mqttOptions.port,
        this.mqttOptions.endpoint + this.patientId
      );
      mqtt.onMessageArrived = onMessageArrived;
      const self = this;
      mqtt.connect({
        onSuccess: onConnect,
        onFailure: onError,
      });
      function onConnect() {
        self.isSetup = true;
        console.log(
          "订阅地址============>",
          `devices/${self.monitor.monitorName}/all/`
        );
        mqtt.subscribe(`devices/${self.monitor.monitorName}/all/`);
      }
      function onError() {
        console.log("Mqtt链接失败");
      }
      function onMessageArrived(message) {
        const res = JSON.parse(message.payloadString);
        const list = res["CaiJiDataItemList"];
        for (let i = 0; i < list.length; i++) {
          self.tizheng[self.dict[list[i].stand_ItemID]] =
            list[i].stand_ItemValue;
        }
      }
    },
  },
};
</script>
